#!/usr/bin/python3

import time
from threading import Thread
from PIL import Image, ImageDraw, ImageFont

from gpiozero import PWMLED, LED

import lcd_driver
import tracer

# gpiozero default mode is BCM
BL_GPIO = 12            # BCM 12
LED_MATRIX_GPIO = 23	# BCM 23, wPi 4

t = tracer.TracerReader('/dev/ttyS0')


def RequestThread():
	t = tracer.TracerReader('/dev/ttyS0')

	# LCD init
	lcd_driver.Open()

	bl = PWMLED(BL_GPIO, active_high=False, initial_value=0, frequency=100)
	bl.value = 1
	# bl.value = 0.2

	led_matrix = LED(LED_MATRIX_GPIO)
	led_matrix.off()

	# Image
	image = Image.new('1', (256, 128))
	draw = ImageDraw.Draw(image)
	font = ImageFont.truetype('fonts/led_board-7.ttf', 30)


	while (True):
		result = t.ReadRealtimeData()
		# print(result)
		# print(result.batt_voltage)
		# print(result.load_amps)
		# print(result.pv_voltage)
		# print(result.charge_current)
		if (result is not None):
			draw.rectangle([(0, 0), (255, 127)], fill=0)
			draw.text((0, 5), 'PV:  {:.2f}V'.format(result.pv_voltage), fill=1, font=font)
			draw.text((0, 35), 'Chg: {:.2f}A'.format(result.charge_current), fill=1, font=font)
			draw.text((0, 65), 'Bat: {:.2f}V'.format(result.batt_voltage), fill=1, font=font)
			draw.text((0, 95), 'Dis: {:.2f}A'.format(result.load_amps), fill=1, font=font)

			lcd_driver.Display(image.tobytes())

			# 判断是否要开关LED的主电源
			if (result.pv_voltage > 5.0):
				led_matrix.off()
			elif (result.pv_voltage < 1.0):
				led_matrix.on()

		time.sleep(1)

t = Thread(target = RequestThread)
t.start()

while(True):
	time.sleep(1)


